package controller.introductionServlet;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import bean.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@WebServlet("/api/message")
public class MessageServlet extends HttpServlet {
    private final Gson gson = new Gson();
    // 简单内存存储（演示用）
    private final List<Message> store = new ArrayList<>();

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 如果跨域请求需要开启下面这些 header（仅示例；生产请限定域名）
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }

    // GET 返回已保存的留言列表（JSON）
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        HashMap<String, Object> out = new HashMap<>();
        out.put("ok", true);
        out.put("messages", store);
        resp.getWriter().write(gson.toJson(out));
    }

    // POST 接收 JSON body -> Message
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        try (BufferedReader reader = req.getReader()) {
            Message m = gson.fromJson(reader, Message.class);
            if (m == null || m.getName() == null || m.getMessage() == null) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                HashMap<String, Object> err = new HashMap<>();
                err.put("ok", false);
                err.put("error", "missing name or message");
                resp.getWriter().write(gson.toJson(err));
                return;
            }
            m.setTimestamp(System.currentTimeMillis());
            store.add(m);

            HashMap<String, Object> out = new HashMap<>();
            out.put("ok", true);
            out.put("message", m);
            resp.getWriter().write(gson.toJson(out));
        } catch (JsonSyntaxException ex) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            HashMap<String, Object> err = new HashMap<>();
            err.put("ok", false);
            err.put("error", "invalid json");
            resp.getWriter().write(gson.toJson(err));
        }
    }
}
